import request from '../../api';
import type { ApiResponse } from '../../api';

// 群组相关类型定义
export interface Group {
  id: string;
  name: string;
  description?: string;
  permissions: string[];
  memberCount: number;
  createTime: string;
  updateTime: string;
  createdBy: string;
}

export interface GroupForm {
  name: string;
  description?: string;
  permissions?: string[];
}

export interface GroupMember {
  id: string;
  userId: string;
  groupId: string;
  username: string;
  email: string;
  avatar?: string;
  joinTime: string;
}

export interface PageRequest {
  page?: number;
  size?: number;
}

export interface PageResponse<T> {
  content?: T[];
  records?: T[];
  totalElements: number;
  totalPages: number;
  size: number;
  number: number;
  first: boolean;
  last: boolean;
}

// 角色组管理API
export const groupApi = {
  // 获取组列表
  getGroups: (params?: PageRequest & { keyword?: string }) => 
    request.get<PageResponse<Group>>('/api/groups', { params }),

  // 获取组详情
  getGroup: (id: string) => 
    request.get<Group>(`/api/groups/${id}`),

  // 创建组
  createGroup: (data: GroupForm) => 
    request.post<Group>('/api/groups', data),

  // 更新组
  updateGroup: (id: string, data: Partial<GroupForm>) => 
    request.put<Group>(`/api/groups/${id}`, data),

  // 删除组
  deleteGroup: (id: string) => 
    request.delete(`/api/groups/${id}`),

  // 批量删除组
  deleteGroups: (ids: string[]) => 
    request.delete('/api/groups/batch', { data: { ids } }),

  // 获取组成员列表
  getGroupMembers: (groupId: string, params?: PageRequest) => 
    request.get<PageResponse<GroupMember>>(`/api/groups/${groupId}/members`, { params }),

  // 添加组成员
  addGroupMembers: (groupId: string, userIds: string[]) => 
    request.post(`/api/groups/${groupId}/members`, { userIds }),

  // 移除组成员
  removeGroupMembers: (groupId: string, userIds: string[]) => 
    request.delete(`/api/groups/${groupId}/members`, { data: { userIds } }),

  // 获取用户可加入的组列表
  getAvailableGroups: (userId: string) => 
    request.get<Group[]>(`/api/users/${userId}/available-groups`),

  // 获取用户所属组列表
  getUserGroups: (userId: string) => 
    request.get<Group[]>(`/api/users/${userId}/groups`),
};

// Mock数据 - 开发环境使用
export const mockGroupApi = {
  getGroups: async (params?: PageRequest & { keyword?: string }): Promise<ApiResponse<PageResponse<Group>>> => {
    await new Promise(resolve => setTimeout(resolve, 300));
    
    const mockGroups: Group[] = [
      {
        id: 'group-001',
        name: '开发团队',
        description: '负责系统开发和维护的技术团队',
        permissions: ['user:read', 'user:write', 'role:read', 'system:read'],
        memberCount: 8,
        createTime: '2024-01-15T10:00:00Z',
        updateTime: '2024-01-20T14:30:00Z',
        createdBy: 'admin',
      },
      {
        id: 'group-002',
        name: '产品团队',
        description: '负责产品规划和需求管理',
        permissions: ['user:read', 'system:read', 'report:read'],
        memberCount: 5,
        createTime: '2024-01-16T09:00:00Z',
        updateTime: '2024-01-18T16:45:00Z',
        createdBy: 'admin',
      },
      {
        id: 'group-003',
        name: '运营团队',
        description: '负责系统运营和用户支持',
        permissions: ['user:read', 'user:write', 'system:read'],
        memberCount: 12,
        createTime: '2024-01-17T11:00:00Z',
        updateTime: '2024-01-19T13:20:00Z',
        createdBy: 'admin',
      },
      {
        id: 'group-004',
        name: '管理团队',
        description: '系统管理员和高级管理人员',
        permissions: ['user:read', 'user:write', 'user:delete', 'role:read', 'role:write', 'role:delete', 'permission:read', 'permission:write', 'system:read', 'system:write'],
        memberCount: 3,
        createTime: '2024-01-10T08:00:00Z',
        updateTime: '2024-01-22T10:15:00Z',
        createdBy: 'admin',
      },
    ];

    let filteredGroups = mockGroups;
    if (params?.keyword) {
      filteredGroups = mockGroups.filter(group => 
        group.name.toLowerCase().includes(params.keyword!.toLowerCase()) ||
        group.description?.toLowerCase().includes(params.keyword!.toLowerCase())
      );
    }

    const page = params?.page || 1;
    const size = params?.size || 10;
    const start = (page - 1) * size;
    const end = start + size;

    return {
      code: 200,
      message: '获取成功',
      data: {
        content: filteredGroups.slice(start, end),
        totalElements: filteredGroups.length,
        totalPages: Math.ceil(filteredGroups.length / size),
        size,
        number: page - 1,
        first: page === 1,
        last: end >= filteredGroups.length,
      },
      timestamp: Date.now(),
    };
  },

  getGroup: async (id: string): Promise<ApiResponse<Group>> => {
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const group = {
      id,
      name: '开发团队',
      description: '负责系统开发和维护的技术团队',
      permissions: ['user:read', 'user:write', 'role:read', 'system:read'],
      memberCount: 8,
      createTime: '2024-01-15T10:00:00Z',
      updateTime: '2024-01-20T14:30:00Z',
      createdBy: 'admin',
    };

    return {
      code: 200,
      message: '获取成功',
      data: group,
      timestamp: Date.now(),
    };
  },

  createGroup: async (data: GroupForm): Promise<ApiResponse<Group>> => {
    await new Promise(resolve => setTimeout(resolve, 500));
    
    const newGroup: Group = {
      id: `group-${Date.now()}`,
      ...data,
      permissions: data.permissions || [],
      memberCount: 0,
      createTime: new Date().toISOString(),
      updateTime: new Date().toISOString(),
      createdBy: 'current-user',
    };

    return {
      code: 200,
      message: '创建成功',
      data: newGroup,
      timestamp: Date.now(),
    };
  },

  updateGroup: async (id: string, data: Partial<GroupForm>): Promise<ApiResponse<Group>> => {
    await new Promise(resolve => setTimeout(resolve, 400));
    
    const updatedGroup: Group = {
      id,
      name: data.name || '开发团队',
      description: data.description,
      permissions: data.permissions || [],
      memberCount: 8,
      createTime: '2024-01-15T10:00:00Z',
      updateTime: new Date().toISOString(),
      createdBy: 'admin',
    };

    return {
      code: 200,
      message: '更新成功',
      data: updatedGroup,
      timestamp: Date.now(),
    };
  },

  deleteGroup: async (_id: string): Promise<ApiResponse<void>> => {
    await new Promise(resolve => setTimeout(resolve, 300));
    
    return {
      code: 200,
      message: '删除成功',
      data: undefined,
      timestamp: Date.now(),
    };
  },

  deleteGroups: async (ids: string[]): Promise<ApiResponse<void>> => {
    await new Promise(resolve => setTimeout(resolve, 400));
    
    return {
      code: 200,
      message: `成功删除 ${ids.length} 个组`,
      data: undefined,
      timestamp: Date.now(),
    };
  },

  getGroupMembers: async (groupId: string, params?: PageRequest): Promise<ApiResponse<PageResponse<GroupMember>>> => {
    await new Promise(resolve => setTimeout(resolve, 300));
    
    const mockMembers: GroupMember[] = [
      {
        id: 'member-001',
        userId: 'user-001',
        groupId,
        username: '张三',
        email: 'zhangsan@v3cloud.com',
        avatar: '',
        joinTime: '2024-01-15T10:00:00Z',
      },
      {
        id: 'member-002',
        userId: 'user-002',
        groupId,
        username: '李四',
        email: 'lisi@v3cloud.com',
        avatar: '',
        joinTime: '2024-01-16T11:00:00Z',
      },
    ];

    const page = params?.page || 1;
    const size = params?.size || 10;
    const start = (page - 1) * size;
    const end = start + size;

    return {
      code: 200,
      message: '获取成功',
      data: {
        content: mockMembers.slice(start, end),
        totalElements: mockMembers.length,
        totalPages: Math.ceil(mockMembers.length / size),
        size,
        number: page - 1,
        first: page === 1,
        last: end >= mockMembers.length,
      },
      timestamp: Date.now(),
    };
  },

  addGroupMembers: async (_groupId: string, userIds: string[]): Promise<ApiResponse<void>> => {
    await new Promise(resolve => setTimeout(resolve, 300));
    
    return {
      code: 200,
      message: `成功添加 ${userIds.length} 个成员`,
      data: undefined,
      timestamp: Date.now(),
    };
  },

  removeGroupMembers: async (_groupId: string, userIds: string[]): Promise<ApiResponse<void>> => {
    await new Promise(resolve => setTimeout(resolve, 300));
    
    return {
      code: 200,
      message: `成功移除 ${userIds.length} 个成员`,
      data: undefined,
      timestamp: Date.now(),
    };
  },
};

// 根据环境选择API
export const api = import.meta.env.DEV ? mockGroupApi : groupApi;
export default api;